<template>
  <el-dialog
    v-model="visible"
    title="多源数据融合配置"
    width="75%"
    top="5vh"
    :close-on-click-modal="false"
    :destroy-on-close="true"
  >
    <div class="fusion-config-container">
      <el-form ref="formRef" :model="form" :rules="rules" label-position="top">
        <el-form-item label="融合模型名称" prop="name">
          <el-input v-model="form.name" placeholder="例如：雨季高风险融合模型"></el-input>
        </el-form-item>
        
        <div class="main-panel">
          <div class="source-panel">
            <div class="panel-header">可选数据源</div>
            <div class="source-list">
              <div
                v-for="source in availableSources"
                :key="source.key"
                class="source-item"
                @click="addSource(source)"
              >
                <el-icon><component :is="source.icon" /></el-icon>
                <span>{{ source.label }}</span>
                <el-icon class="add-icon"><CirclePlusFilled /></el-icon>
              </div>
            </div>
          </div>

          <div class="config-panel">
            <div class="panel-header">
              已选融合数据（可拖拽排序）
              <span class="total-weight" :class="weightStatus.class">
                总权重: {{ totalWeight }}%
              </span>
            </div>
            
            <draggable
                v-model="form.selectedSources"
                item-key="key"
                handle=".drag-handle"
                class="config-list"
                ghost-class="ghost"
              >
              <template #item="{ element: source }">
                <div class="config-item">
                  <el-icon class="drag-handle" title="拖拽排序"><Rank /></el-icon>
                  
                  <div class="config-content">
                    <div class="config-header">
                      <el-radio-group v-model="form.primarySource" size="small">
                         <el-radio 
                          :label="source.key" 
                          :disabled="source.type !== 'deformation'"
                          title="设为主数据源"
                        >
                          <span class="source-label">
                            <el-icon><component :is="source.icon" /></el-icon>
                            {{ source.label }}
                          </span>
                        </el-radio>
                      </el-radio-group>
                    </div>

                    <div class="config-body">
                      <el-form-item label="权重 (%)" class="weight-item">
                        <el-input-number v-model="source.weight" :min="0" :max="100" :step="5" controls-position="right" size="small"/>
                      </el-form-item>
                      <el-button text type="primary" size="small">高级设置</el-button>
                    </div>
                  </div>

                  <el-button
                    @click="removeSource(source)"
                    type="danger"
                    :icon="Delete"
                    circle
                    plain
                    class="remove-btn"
                  />
                </div>
              </template>
            </draggable>
            <el-empty v-if="form.selectedSources.length === 0" description="请从左侧添加数据源" />
          </div>
        </div>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">关闭</el-button>
        <el-button type="primary" @click="handleSave">保存配置</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import draggable from "vuedraggable"; // 引入 draggable
// 引入图标
import {
  Aim, Location, Watermelon, Cloudy, Sunrise, Delete, Rank, CirclePlusFilled
} from '@element-plus/icons-vue';

// --- 类型定义 ---
interface DataSource {
  key: string;
  label: string;
  icon: any; // 组件类型
  type: 'deformation' | 'trigger'; // 数据类型：形变或诱发因素
  weight: number;
}

// --- state ---
const visible = ref<boolean>(false);
const formRef = ref<FormInstance>();

// 所有可选的数据源
const allSources = reactive<DataSource[]>([
  { key: 'gnss', label: 'GNSS数据', icon: Aim, type: 'deformation', weight: 40 },
  { key: 'total_station', label: '全站仪数据', icon: Location, type: 'deformation', weight: 30 },
  { key: 'insar', label: 'InSAR数据', icon: Watermelon, type: 'deformation', weight: 20 },
  { key: 'groundwater', label: '地下水位数据', icon: Sunrise, type: 'trigger', weight: 5 },
  { key: 'rainfall', label: '降雨量数据', icon: Cloudy, type: 'trigger', weight: 5 },
]);

const form = reactive({
  name: "",
  primarySource: "", // 主数据源的 key
  selectedSources: [] as DataSource[],
});

const rules = reactive<FormRules>({
  name: [{ required: true, message: "请输入融合模型名称", trigger: "blur" }],
});

// --- computed ---

// 计算尚未选择的数据源
const availableSources = computed(() => {
  const selectedKeys = form.selectedSources.map(s => s.key);
  return allSources.filter(s => !selectedKeys.includes(s.key));
});

// 计算总权重
const totalWeight = computed(() => {
  return form.selectedSources.reduce((sum, source) => sum + (source.weight || 0), 0);
});

// 根据总权重返回状态
const weightStatus = computed(() => {
  if (totalWeight.value === 100) return { class: 'valid', text: '有效' };
  if (totalWeight.value > 100) return { class: 'invalid', text: '超额' };
  return { class: 'incomplete', text: '不足' };
});


// --- methods ---

const addSource = (source: DataSource) => {
  form.selectedSources.push({ ...source });
  // 如果是第一个添加的形变数据，默认设为主数据源
  if (!form.primarySource && source.type === 'deformation') {
    form.primarySource = source.key;
  }
};

const removeSource = (sourceToRemove: DataSource) => {
  form.selectedSources = form.selectedSources.filter(s => s.key !== sourceToRemove.key);
  // 如果移除的是主数据源，清空主数据源选择
  if (form.primarySource === sourceToRemove.key) {
    form.primarySource = "";
    // 自动选择下一个形变数据作为主数据源
    const nextDeformationSource = form.selectedSources.find(s => s.type === 'deformation');
    if (nextDeformationSource) {
      form.primarySource = nextDeformationSource.key;
    }
  }
};

const handleSave = async () => {
  if (!formRef.value) return;
  await formRef.value.validate((valid) => {
    if (valid) {
      if (form.selectedSources.length < 2) {
        ElMessage.warning("请至少选择两个数据源进行融合");
        return;
      }
      if (!form.primarySource) {
        ElMessage.warning("请指定一个主数据源");
        return;
      }
      if (totalWeight.value !== 100) {
        ElMessage.warning("所有数据源的权重之和必须等于100%");
        return;
      }

      // 构造最终要提交的数据
      const fusionConfig = {
        name: form.name,
        primarySource: form.primarySource,
        sources: form.selectedSources.map(s => ({ key: s.key, weight: s.weight })),
        // 还可以包含排序信息
        order: form.selectedSources.map(s => s.key),
      };

      console.log("保存的融合配置:", fusionConfig);
      ElMessage.success("保存成功！");
      close();
    }
  });
};

const open = () => {
  // 这里可以接收一个已有的配置用于编辑，此处为新建
  form.name = "";
  form.selectedSources = [];
  form.primarySource = "";
  visible.value = true;
};

const close = () => {
  visible.value = false;
};

defineExpose({ open, close });
</script>

<style scoped>
.fusion-config-container {
  max-height: 75vh;
  overflow-y: auto;
  padding: 0 10px;
}
.main-panel {
  display: flex;
  gap: 20px;
  margin-top: 10px;
}
.source-panel, .config-panel {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 50%;
}
.panel-header {
  background-color: #f5f7fa;
  padding: 10px 15px;
  font-weight: bold;
  border-bottom: 1px solid #dcdfe6;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.source-list, .config-list {
  padding: 10px;
  min-height: 300px;
}
.source-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.2s;
}
.source-item:hover {
  background-color: #ecf5ff;
}
.source-item .el-icon {
  margin-right: 8px;
  font-size: 16px;
}
.source-item .add-icon {
  margin-left: auto;
  color: #409eff;
  visibility: hidden;
  opacity: 0;
  transition: opacity 0.2s;
}
.source-item:hover .add-icon {
  visibility: visible;
  opacity: 1;
}

.config-item {
  display: flex;
  align-items: center;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 10px;
  background: #fff;
}
.config-content {
  flex-grow: 1;
}
.config-header {
  margin-bottom: 10px;
}
.source-label {
  display: flex;
  align-items: center;
  font-size: 14px;
}
.source-label .el-icon {
  margin-right: 5px;
}
.config-body {
  display: flex;
  align-items: center;
  gap: 15px;
}
.weight-item {
  margin-bottom: 0;
}
.drag-handle {
  cursor: grab;
  color: #909399;
  margin-right: 10px;
  font-size: 18px;
}
.drag-handle:active {
  cursor: grabbing;
}
.remove-btn {
  margin-left: 10px;
}
.total-weight {
  font-size: 13px;
  font-weight: normal;
}
.total-weight.valid { color: #67c23a; }
.total-weight.invalid { color: #f56c6c; }
.total-weight.incomplete { color: #e6a23c; }

/* vuedraggable ghost class */
.ghost {
  opacity: 0.5;
  background: #c8ebfb;
}
</style>